//
//  main.c
//  iconvtest
//
//  Created by 杨岑 on 1/31/16.
//  Copyright © 2016 杨岑. All rights reserved.
//

#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
//#include <wchar.h>
//#include <locale.h>
#include <iconv.h>


#define BYTE_TO_INT(x) (((int)x) & 0xff)

int main(int argc, char* argv[])
{
    iconv_t t = iconv_open("UTF-16", "utf-8");
    if (t != (iconv_t)-1)
    {
        char* srcString = argc > 1 ? argv[1] : "中文test测试";
        size_t srcStringSize = strlen(srcString);
        printf("Source string: %zu bytes %s\n", srcStringSize, srcString);
        for (int i = 0; i < srcStringSize; i++)
        {
            printf("%02x,", BYTE_TO_INT(srcString[i]));
        }
        puts("\n");
        
        size_t resultBufSize = (srcStringSize + 2) * 4; // max 4 bytes for 1 byte
        char* resultString = malloc(resultBufSize);
        if (resultString)
        {
            size_t srcSize = srcStringSize + 1; // Including \0
            size_t dstSize = resultBufSize;
            char* psrc = srcString;
            char* pdst = resultString;
            size_t rc = iconv(t, &psrc, &srcSize, &pdst, &dstSize);
            if (rc != (size_t)-1)
            {
                //setlocale(LC_ALL, "");
                size_t converted = resultBufSize - dstSize;
                printf("Converted to %zu bytes\n", converted);
                //wprintf(L"Converted to %zu bytes %S\n", converted, resultString + 2);
                for (int i = 0; i < converted; i++)
                {
                    printf("%02x,", BYTE_TO_INT(resultString[i]));
                }
                puts("");
            }
            else
            {
                printf("iconv error %d:\n", errno);
                perror(0);
            }
            free(resultString);
        }
        else
        {
            printf("Out of memory requesting %lu bytes\n", resultBufSize);
        }
        iconv_close(t);
    }
    else
    {
        puts("iconv_open failed");
    }
    return 0;
}
